import numpy as np

x = np.array([[1.0, 1.1],
              [1.0, 1.0],
              [0, 0],
              [0, 0.1]])
y = np.array([0, 0, 1, 1])


# print(x, y)

def knn(_x, k=3):
    # 计算距离
    # d = sqrt (x1-x2)**2 + (y1-y2)**2
    temp = _x - x
    print(temp)
    # [[-0.9 -1. ]
    #  [-0.9 -0.9]
    #  [ 0.1  0.1]
    #  [ 0.1  0. ]]
    temp = np.power(temp, 2)
    # [[0.81 1.  ]
    #  [0.81 0.81]
    #  [0.01 0.01]
    #  [0.01 0.  ]]
    print(temp)
    temp = temp.sum(axis=1)
    # [1.81 1.62 0.02 0.01]
    print(temp)
    temp = np.sqrt(temp)
    # [1.3453624  1.27279221 0.14142136 0.1       ]
    print(temp)
    argsort = temp.argsort() # [3 2 1 0]
    print(argsort)
    result = y[argsort][:k] # [1 1 0]
    print(result)
    return np.bincount(result).argmax() # 取众数


if __name__ == '__main__':
    print(knn(np.array([0.1, 0.1])))
